/*
 *    Copyright (c) 2018-2025, boss All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the boss developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: boss
 */

package com.hopes.bizz.enforcement.integral.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hopes.bizz.common.core.util.StringUtils;
import com.hopes.bizz.enforcement.common.constant.enums.EnforcementModDictEnum;
import com.hopes.bizz.enforcement.common.constant.enums.EnforcementSysDictEnum;
import com.hopes.bizz.enforcement.integral.dto.RiskIntegralStatisticalDTO;
import com.hopes.bizz.enforcement.integral.entity.RiskIntegralRecordEntity;
import com.hopes.bizz.enforcement.integral.entity.RiskIntegralStatisticalEntity;
import com.hopes.bizz.enforcement.integral.service.RiskIntegralRecordService;
import com.hopes.bizz.enforcement.integral.service.RiskIntegralStatisticalService;
import com.hopes.bizz.enforcement.integral.vo.RiskIntegralStatisticalVO;
import com.hopes.boss.admin.api.entity.SysDictItem;
import com.hopes.boss.admin.api.resolver.DictResolver;
import com.hopes.boss.admin.api.resolver.enums.AdminDictEnum;
import com.hopes.boss.common.core.util.R;
import com.hopes.boss.common.log.annotation.SysLog;
import com.hopes.boss.common.security.util.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 个人积分统计
 *
 * @author daijie
 * @date 2023-07-20 15:16:50
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/riskIntegralStatistical" )
@Tag(description = "riskIntegralStatistical" , name = "个人积分统计管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class RiskIntegralStatisticalController {

    private final RiskIntegralStatisticalService riskIntegralStatisticalService;
    private final RiskIntegralRecordService riskIntegralRecordService;

    /**
     * 分页查询
     * @param page 分页对象
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('basic_integral_statistical_view')" )
    public R getriskIntegralStatisticalPage(Page page, RiskIntegralStatisticalDTO dto) {
        LambdaQueryWrapper<RiskIntegralStatisticalEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ObjectUtil.isNotNull(dto.getAccountId()), RiskIntegralStatisticalEntity::getAccountId, dto.getAccountId());
        if (ObjectUtil.isNotNull(dto.getDeptId())) {
            String userIds = DictResolver.getItemLabelByValue(AdminDictEnum.sys_dept2user, dto.getDeptId());
            if (StringUtils.isNotBlank(userIds)) {
                List<Long> ids = Arrays.stream(userIds.split(StringUtils.COMMA)).map(Long::parseLong).collect(Collectors.toList());
                wrapper.in(RiskIntegralStatisticalEntity::getAccountId, ids);
            }
        }

        Page pageInfo = riskIntegralStatisticalService.page(page, wrapper);
        List<RiskIntegralStatisticalVO> voList = new ArrayList<>();
        for (Object record : pageInfo.getRecords()) {
            RiskIntegralStatisticalVO vo = new RiskIntegralStatisticalVO();
            BeanUtils.copyProperties(record, vo);
            voList.add(vo);
        }
        pageInfo.setRecords(voList);
        return R.ok(pageInfo);
    }

    @Operation(summary = "查询个人积分统计列表" , description = "查询个人积分统计列表" )
    @GetMapping(value = "/listMyStatistical")
    @PreAuthorize("@pms.hasPermission('basic_integral_statistical_view')" )
    public R listMyStatistical() {
        Map resMap = new HashMap<>();
        resMap.put("integralStatistical", Collections.emptyList());
        RiskIntegralStatisticalEntity entity = riskIntegralStatisticalService.getByAccount(SecurityUtils.getUser().getId());
        if (entity != null) {
            resMap.put("integralStatistical", Collections.singletonList(entity));
        }
        LambdaQueryWrapper<RiskIntegralRecordEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(RiskIntegralRecordEntity::getAccountId, SecurityUtils.getUser().getId());
        List<RiskIntegralRecordEntity> recordList = riskIntegralRecordService.list(wrapper);

        Map statisticalMap = new HashMap<>();
        resMap.put("statistical", statisticalMap);
        List<SysDictItem> eventList = DictResolver.getItemsByType(EnforcementModDictEnum.risk_integral_event_and_value);
        if (eventList !=null && !eventList.isEmpty()) {
            Map<Integer, Integer> eventMap = eventList.stream().collect(Collectors.toMap(event -> Integer.valueOf(event.getName()), event -> 0));
            Map<Integer, List<RiskIntegralRecordEntity>> map = recordList.stream().collect(Collectors.groupingBy(RiskIntegralRecordEntity::getEventName));
            map.forEach((event, list) -> eventMap.put(event, list.size()));

            eventMap.forEach((event, len) -> {
                String eventName = DictResolver.getItemLabelByValue(EnforcementSysDictEnum.basic_integral_event, event);
                statisticalMap.put(eventName, len);
            });
            resMap.put("statistical", statisticalMap);
        }

        return R.ok(resMap);
    }

    /**
     * 通过id查询个人积分统计
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询" , description = "通过id查询" )
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('basic_integral_statistical_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(riskIntegralStatisticalService.getById(id));
    }

    /**
     * 新增个人积分统计
     * @param riskIntegralStatistical 个人积分统计
     * @return R
     */
    @Operation(summary = "新增个人积分统计" , description = "新增个人积分统计" )
    @SysLog("新增个人积分统计" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('basic_integral_statistical_add')" )
    public R save(@RequestBody RiskIntegralStatisticalEntity riskIntegralStatistical) {
        return R.ok(riskIntegralStatisticalService.save(riskIntegralStatistical));
    }

    /**
     * 修改个人积分统计
     * @param riskIntegralStatistical 个人积分统计
     * @return R
     */
    @Operation(summary = "修改个人积分统计" , description = "修改个人积分统计" )
    @SysLog("修改个人积分统计" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('basic_integral_statistical_edit')" )
    public R updateById(@RequestBody RiskIntegralStatisticalEntity riskIntegralStatistical) {
        return R.ok(riskIntegralStatisticalService.updateById(riskIntegralStatistical));
    }

    /**
     * 通过id删除个人积分统计
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除个人积分统计" , description = "通过id删除个人积分统计" )
    @SysLog("通过id删除个人积分统计" )
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('basic_integral_statistical_del')" )
    public R removeById(@RequestBody Long[] ids) {
        return R.ok(riskIntegralStatisticalService.removeBatchByIds(CollUtil.toList(ids)));
    }
}
